package server

import (
	"fmt"
	"os"
	"strings"
)

const (
	HADOOP                   = "hadoop"
	HADOOP_NAMENODE          = "namenode"
	HADOOP_SECONDARYNAMENODE = "secondarynamenode"
	HADOOP_RESOURCEMANAGER   = "resourcemanager"
	HADOOP_NODEMANAGER       = "nodemanager"
	HADOOP_DATANODE          = "datanode"
)

type Step struct {
	Name   string `json:"name"`
	Status int    `json:"status"`
}

type Comp struct {
	Name   string `json:"name"`
	Type   string `json:"type"`
	Status int    `json:"status"`
}

// status的值的含义
type ClusterInfo struct {
	ClusterId string `json:"clusterId"`
	Name      string `json:"name"`
	Comp      string `json:"comp"`
	Type      string `json:"type"`
	Mode      string `json:"[sa]mode"`
	Status    int    `json:"status"`
}

type NodeInfo struct {
	Ip       string `json:"ip"`
	Hostname string `json:"hostname"`
	Auths    string `json:"auths"`
	Status   int    `json:"status"`
}

type RoleInfo struct {
	Ip     string `json:"ip"`
	Name   string `json:"name"`
	Status int    `json:"status"`
}

func (m *Master) GenRoleOrder(comp string, roles string) []string {
	orderRoles := make([]string, 0)
	if strings.Contains(comp, HADOOP) {
		if strings.Contains(roles, HADOOP_NAMENODE) {
			orderRoles = append(orderRoles, HADOOP_NAMENODE)
		}
		if strings.Contains(roles, HADOOP_SECONDARYNAMENODE) {
			orderRoles = append(orderRoles, HADOOP_SECONDARYNAMENODE)
		}
		if strings.Contains(roles, HADOOP_RESOURCEMANAGER) {
			orderRoles = append(orderRoles, HADOOP_RESOURCEMANAGER)
		}
		if strings.Contains(roles, HADOOP_NODEMANAGER) {
			orderRoles = append(orderRoles, HADOOP_NODEMANAGER)
		}
		if strings.Contains(roles, HADOOP_DATANODE) {
			orderRoles = append(orderRoles, HADOOP_DATANODE)
		}
	}
	return orderRoles
}

func (m *Master) GenCheckRoleStatusScript(comp string) string {
	script := ""
	if strings.Contains(comp, HADOOP) {
		script = "jps"
	}
	return script
}

func (m *Master) UpdateProgressStatus(clusterId string, index int, status int64) {
	progressPath := fmt.Sprintf("%s/%s", m.Config.MasterConfig.ProgressPath, clusterId)
	progressData, _ := os.ReadFile(progressPath)
	progress := strings.Split(string(progressData), "\n")
	step := strings.Split(progress[index], ",")
	progress[index] = fmt.Sprintf("%s,%d", step[0], status)
	os.WriteFile(progressPath, []byte(strings.Join(progress, "\n")), 0644)
}
